<template>
  <van-form @submit="onSubmit">
    <img src="https://b.bdstatic.com/searchbox/icms/searchbox/img/jd-newlogo.jpeg">
  <van-cell-group inset>
    <van-field
      v-model="status.username"
      name="用户名"
      label="用户名"
      placeholder="请输入用户名"
      clearable
      :rules="[{ required: true, message: '请填写用户名' }]"
    />
    <van-field
      v-model="status.password"
      type="password"
      name="密码"
      label="密码"
      placeholder="请输入密码"
      clearable
      v-if="status.isPassword"
      :rules="[{ required: true, message: '请填写密码' }]"
    />
    <van-field
      v-model="status.captcha"
      name="验证码"
      label="验证码"
      placeholder="请输入验证码"
      clearable
      v-else
      :rules="[{ required: true, message: '请填入验证码' }]">
      <template #button>
      <van-button size="small" type="primary"
      @click="sendCaptcha" :disabled="status.isSend">{{ status.currentText}}</van-button>
      </template>
    </van-field>
  </van-cell-group>
  <div style="margin: 16px;">
    <van-button round block type="primary" @click = "onSubmit">
      登录</van-button>
  </div>
  <span class="meg" @click="handleLoginMode" v-text="status.changeText"></span>
</van-form>

</template>
<script setup>
import { Button as VanButton, Form as VanForm, 
  CellGroup as vanCellGroup, Field as VanField } from 'vant'
// import { getLogo } from '@/api/home'
import { getUserCode, getMsgCode, loginByPassword, loginByMobile } from '@/api/user.js'
import { useCountDown } from '@vant/use';
import { computed } from '@vue/reactivity';
import { Toast } from 'vant';
import { reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex'
const store = useStore()
const router = useRouter()
const route = useRoute()
// ----- 基本数据处理 ----
const status = reactive({
  username: '',
  password: '',
  captcha: '',
  // 登录模式
  loginMode: 'password',
  // 检测是否是登录模式
  isPassword: computed(() => status.loginMode === 'password'),
  // 切换按钮文本
  changeText: computed(() => status.isPassword ? '快速登录' : '密码登录'),
  // 存储发送验证码的状态 用于控制秒数的显示效果
  isSend: false,
  // 显示倒计时信息的状态
  countDown: null,
  // 根据状态设置要显示的内容
  currentText: computed(() => status.isSend ? status.countDown.seconds : '发送验证码')

})
// 登录切换模式
function handleLoginMode () {
  status.loginMode = status.isPassword ? '1' : 'password'
  // 清除密码与验证码 输入的内容
  status.username = ''
  status.password = ''

}


// ---- 验证码处理 ----
// 发送验证码请求
const sendCaptcha = async () => {
  // 手机号规则的校验
  if (!/^1\d{10}$/.test(status.username)) {
    return Toast('请输入正确的用户名')
  }
  // 发送校验请求(用户验证码)
  const { data: v1 } = await getUserCode()
  // console.log(data)
  if(v1.status !== 200) {
    return    
  }
  // 发送验证码请求 (获取短信验证码)
  const { data: v2 } = await getMsgCode({
    key: v1.data.key,
    phone: status.username,
    type: 'login'
  })
  // console.log(v2)
  if(v2.status !== 200) { Toast('请输入正确的验证码')}

  // 倒计时处理
  const countDown = useCountDown({
    // 倒计时 60 S
      time: 6 * 1000,
      // status.isSend = true
      onFinish () {
        status.isSend = false
      }
    })
    // 开始倒计时
    countDown.start()
    status.countDown = countDown.current
    // 开始倒计时后发送状态改为true 文本变为剩余秒数
    status.isSend = true
}



// ---- 登录处理-----
const onSubmit = async () => {
  // 用户名检测 
  // trim() 方法用于删除字符串的头尾空白符，空白符包括：空格、制表符 tab、换行符等其他空白符等。
  const username = status.username.trim()
  if (username === ''){
    return Toast('请输入用户名')
  }
  // 密码模式和验证码模式的统一管理 使用全局变量存储
  let data = {}
  if (status.isPassword) {
    // 密码模式
    const password = status.password.trim()
    if (password === ''){
    return Toast('请输入密码')
    }
    ({ data } = await loginByPassword({
      account: username,
      password: password
    }))
    // console.log(v1)
  } else {
    // 验证码模式
    const captcha = status.captcha.trim()
    if (captcha === ''){
    return Toast('请输入验证码')
    }
    ({ data } = await loginByMobile({
      phone: username,
      captcha: captcha
    }))
  }
    // console.log(v2)
    console.log(data)
    if(data.status !== 200){return Toast('用户名或密码错误')} 
    // 提交新的的token信息通过mutation使用commit
    store.commit('user/setUser', data.data.token)
    // 跳转页面
    router.push(route.query.redirect ?? '/user')
}

// ----  头像处理 ----
// const loadLogo = async () => {
//   const { data } = await getLogo()
//   if (data.status !==200) { return }
//   // console.log(data)
// }
// loadLogo()
</script>
<style lang='scss' scoped>
.van-form{
  display: flex;
  flex-direction: column;
  :deep(img){
    width: 120px;
    height: 120px;
    align-self: center;
    margin: 50px auto;
    border-radius: 20px;
  }
  .meg{
    font-size: 14px;
    align-self: center;
    color: #999;
  }
}

</style>
 